<template>
  <div class="products-page">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="filterForm.keyword" placeholder="搜索商品名称" clearable @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="filterForm.categoryId" placeholder="请选择分类" clearable style="width: 150px">
              <el-option v-for=" category in categories" :key="category.id" :label="category.name"
              :value="category.id" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 商品列表 -->
    <div class="products-section">
      <div class="section-header">
        <h2>
          {{ getPageTitle() }}
        </h2>
        <!-- <el-button @click="loadDefaultProducts" type="info" size="small">
          加载默认数据
        </el-button> -->
      </div>

      <div v-loading="loading" class="products-grid">
        <div v-for="product in products" :key="product.id" class="product-card" @click="handleProductClick(product)">
          <div class="product-image">
            <el-image :src="getProductImage(product)" fit="cover" class="image">
              <template #error>
                <div class="image-error">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
            <!-- <div class="product-status">
              <el-tag :type="getStatusType(product.status)" size="small">
                {{ getStatusText(product.status) }}
              </el-tag>
            </div> -->
            <div v-if="product.isBargain === true" class="bargain-tag">可砍价</div>
          </div>

          <div class="product-info">
            <div class="product-title">{{ product.name }}</div>
                         <div class="product-owner">
               <span class="owner-label">卖家：</span>
               <span class="owner-name">{{ maskUserName(userInfoMap.get(product.userId)?.userName || userInfoMap.get(product.userId)?.userAccount || '未知用户') }}</span>
             </div>
            <div class="product-meta">{{ product.detail }}</div>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <!-- <span class="original-price" v-if="product.originalPrice && product.originalPrice > product.price">
                ¥{{ product.originalPrice }}
              </span> -->
            </div>
            <!-- <div class="product-meta">
              <span class="seller">{{ product.sellerName || '未知卖家' }}</span>
              <span class="time">{{ formatTime(product.createTime) }}</span>
            </div> -->
            <div class="product-stats">
              <span class="likes">
                库存 {{ product.inventory || 0 }}
              </span>
              <span class="views">
                <el-icon size="12">
                  <View />
                </el-icon>
                {{ getOldLevelText(product.oldLevel || 50) }}
              </span>
            </div>
            <!-- <div class="product-actions">
              <el-button
                size="small"
                type="primary"
                @click.stop="handleBuy(product)"
                :disabled="product.status === 2"
              >
                {{ product.status === 2 ? '已售出' : '立即购买' }}
              </el-button>
              <el-button
                size="small"
                :type="product.isFavorited ? 'danger' : 'default'"
                @click.stop="handleFavorite(product)"
              >
                {{ product.isFavorited ? '取消收藏' : '收藏' }}
              </el-button>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[12, 24, 36, 48]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import { Product, Category } from '@/types'
import { ElMessage } from 'element-plus'
import { Picture, View } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import request from '@/utils/request'
import { getOldLevelText, maskUserName } from '@/utils/product'

const route = useRoute()
const router = useRouter()
const productStore = useProductStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const products = ref<Product[]>([])
const categories = ref<Category[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const userInfoMap = ref<Map<number, any>>(new Map())

// 筛选表单
const filterForm = reactive({
  keyword: '',
  categoryId: undefined as number | undefined,
  canBargain: undefined as boolean | undefined
})

// 计算属性
const queryParams = computed(() => ({
  pageNum: currentPage.value,
  pageSize: pageSize.value,
  name: filterForm.keyword,
  categoryId: filterForm.categoryId,
  isBargain: filterForm.canBargain ? 1 : filterForm.canBargain === false ? 0 : undefined
}))

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  
  try {
    const userInfo = await userStore.getUserById(userId)
    if (userInfo) {
      userInfoMap.value.set(userId, userInfo)
    }
    return userInfo
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 默认商品数据
const getDefaultProducts = () => {
  return [
  ]
}

// 方法
const loadProducts = async () => {
  loading.value = true
  try {
    console.log('尝试加载商品数据，参数:', queryParams.value)
    const response = await productStore.getProducts(queryParams.value)
    console.log('商品API响应:', response)
    
    if (response && response.list) {
      products.value = response.list
      total.value = response.total
      console.log('成功加载商品数据:', products.value.length, '个商品')
      
      // 为每个商品获取用户信息
      for (const product of products.value) {
        if (product.userId) {
          await fetchUserInfo(product.userId)
        }
      }
    } else {
      throw new Error('商品数据格式错误')
    }
  } catch (error) {
    console.error('加载商品失败:', error)
    ElMessage.warning('无法连接到服务器')
    
    // 直接调用默认数据加载方法
    loadDefaultProducts()
  } finally {
    loading.value = false
  }
}

// 强制加载默认数据的方法
const loadDefaultProducts = () => {
  console.log('强制加载默认商品数据')
  const defaultProducts = getDefaultProducts()
  products.value = defaultProducts.slice(0, pageSize.value)
  total.value = defaultProducts.length
  console.log('默认商品数据已加载:', products.value.length, '个商品')
}

const loadCategories = async () => {
  try {
    // 调用后端分类接口获取分类列表
    const response = await request.get('/category/list', {
      params: {
        pageSize:20,
      }
    })
    console.log('分类API响应:', response)
    
    // 检查响应数据结构
    if (response && response.data) {
      // 确保response.data是数组
      const categoryData = Array.isArray(response.data) ? response.data : 
                          (response.data.data && Array.isArray(response.data.data)) ? response.data.data : []
      
      if (categoryData.length > 0) {
        categories.value = categoryData.filter((cat: Category) => cat.isUse)
      } else {
        throw new Error('分类数据为空')
      }
    } else {
      throw new Error('分类API响应格式错误')
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API不可用，使用默认分类
    categories.value = [
      { id: 1, name: '电子产品', isUse: true },
      { id: 2, name: '服装配饰', isUse: true },
      { id: 3, name: '家居用品', isUse: true },
      { id: 4, name: '运动户外', isUse: true },
      { id: 5, name: '图书音像', isUse: true }
    ]
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

const handleReset = () => {
  filterForm.keyword = ''
  filterForm.categoryId = undefined
  filterForm.canBargain = undefined
  currentPage.value = 1
  loadProducts()
}



const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadProducts()
}

// const scanDate = reactive(
//   {
    
//   }
// )
const handleProductClick = (product: Product) => {
  //新增浏览历史记录
  //const response = request.post('/interaction/add')
  router.push(`/product/${product.id}`)
}

// const handleBuy = (product: Product) => {
//   if (product.status === 2) {
//     ElMessage.warning('该商品已售出')
//     return
//   }
//   router.push(`/product/${product.id}`)
// }

// const handleFavorite = async (product: Product) => {
//   try {
//     if (product.isFavorited) {
//       await productStore.unfavoriteProduct(product.id)
//       ElMessage.success('已取消收藏')
//     } else {
//       await productStore.favoriteProduct(product.id)
//       ElMessage.success('已添加到收藏')
//     }
//     // 重新加载商品列表以更新收藏状态
//     loadProducts()
//   } catch (error) {
//     ElMessage.error('操作失败')
//   }
// }

const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

// 处理商品图片
const getProductImage = (product: Product) => {
  if (product.coverList && product.coverList.length > 0) {
    return product.coverList
  }
  return '/placeholder.svg'
}

const getProductImages = (product: Product) => {
  if (product.coverList && product.coverList.length > 0) {
    return product.coverList
  }
  return []
}

// 获取页面标题
const getPageTitle = () => {
  if (filterForm.categoryId) {
    const category = categories.value.find(cat => cat.id === filterForm.categoryId)
    if (category) {
      return `${category.name} - 商品列表`
    }
  }
  if (filterForm.keyword) {
    return `搜索"${filterForm.keyword}" - 商品列表`
  }
  return '商品列表'
}

// 获取状态类型
// const getStatusType = (status: number) => {
//   switch (status) {
//     case 0: return 'info'
//     case 1: return 'success'
//     case 2: return 'warning'
//     default: return 'info'
//   }
// }

// 获取状态文本
// const getStatusText = (status: number) => {
//   switch (status) {
//     case 0: return '下架'
//     case 1: return '在售'
//     case 2: return '已售'
//     default: return '未知'
//   }
// }

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  // 更新筛选条件
  if (newQuery.keyword !== undefined) {
    filterForm.keyword = newQuery.keyword as string
  }
  if (newQuery.categoryId !== undefined) {
    filterForm.categoryId = Number(newQuery.categoryId)
  }
  
  // 重新加载商品数据
  currentPage.value = 1
  loadProducts()
}, { immediate: false })

// 生命周期
onMounted(async () => {
  // 从路由参数中获取初始筛选条件
  if (route.query.keyword) {
    filterForm.keyword = route.query.keyword as string
  }
  if (route.query.categoryId) {
    filterForm.categoryId = Number(route.query.categoryId)
  }
  
  // 先加载分类，如果失败不影响商品显示
  try {
    await loadCategories()
  } catch (error) {
    console.error('分类加载失败，使用默认分类:', error)
  }
  
  // 尝试加载商品数据，如果失败则使用默认数据
  try {
    await loadProducts()
  } catch (error) {
    console.error('商品加载失败', error)
    loadDefaultProducts()
  }
})
</script>

<style scoped>
.products-page {
  min-height: 100vh;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 30px;
}

.filter-section :deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 107, 53, 0.1);
  overflow: hidden;
}

.filter-section :deep(.el-card__body) {
  padding: 25px;
}

.filter-section :deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-end;
}

.filter-section :deep(.el-form-item) {
  margin-bottom: 0;
  flex: 1;
  min-width: 200px;
}

.filter-section :deep(.el-input__wrapper) {
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  transition: all 0.3s ease;
  box-shadow: none;
}

.filter-section :deep(.el-input__wrapper:hover) {
  border-color: #ff6b35;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 107, 53, 0.1);
}

.filter-section :deep(.el-input__wrapper.is-focus) {
  border-color: #ff6b35;
  box-shadow: 0 8px 25px rgba(255, 107, 53, 0.15);
}

.filter-section :deep(.el-select) {
  width: 100%;
}

.filter-section :deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  padding: 12px 24px;
  transition: all 0.3s ease;
}

.filter-section :deep(.el-button--primary) {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  border: none;
}

.filter-section :deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 53, 0.3);
}

.filter-section :deep(.el-button--default) {
  border: 2px solid #e1e8ed;
  color: #5a6c7d;
}

.filter-section :deep(.el-button--default:hover) {
  border-color: #ff6b35;
  color: #ff6b35;
  transform: translateY(-2px);
}

/* 商品列表区域样式 */
.products-section {
  margin-bottom: 50px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  position: relative;
}

.section-header h2::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #ff6b35, #f7931e);
  border-radius: 2px;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 商品网格样式 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.product-card {
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f0f0f0;
  background: #fff;
  position: relative;
}

.product-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 40px rgba(255, 107, 53, 0.15);
  border-color: #ff6b35;
}

.product-image {
  position: relative;
  height: 280px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  transition: transform 0.4s ease;
}

.product-card:hover .image {
  transform: scale(1.05);
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  color: #adb5bd;
  font-size: 14px;
  gap: 8px;
}

.product-status {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 2;
}

.bargain-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #f56c6c 0%, #ff6b8a 100%);
  color: #fff;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
  z-index: 2;
}

.product-info {
  padding: 20px;
}

.product-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
  line-height: 1.4;
  min-height: 44px;
}

.product-owner {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.owner-label {
  color: #999;
}

.owner-name {
  color: #4facfe;
  font-weight: 500;
}

.product-meta {
  margin-bottom: 12px;
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  margin-bottom: 12px;
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.current-price {
  font-size: 24px;
  font-weight: 700;
  color: #ff6b35;
  line-height: 1;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.seller {
  font-weight: 500;
}

.time {
  font-size: 12px;
  color: #999;
}

.product-stats {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #7f8c8d;
  margin-bottom: 15px;
}

.likes, .views {
  display: flex;
  align-items: center;
  gap: 4px;
}

.product-actions {
  display: flex;
  gap: 10px;
}

.product-actions .el-button {
  flex: 1;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.product-actions .el-button--primary {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  border: none;
}

.product-actions .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 107, 53, 0.3);
}

.product-actions .el-button--default {
  border: 2px solid #e1e8ed;
  color: #5a6c7d;
}

.product-actions .el-button--default:hover {
  border-color: #ff6b35;
  color: #ff6b35;
  transform: translateY(-2px);
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.pagination-section :deep(.el-pagination) {
  --el-pagination-bg-color: #fff;
  --el-pagination-border-radius: 12px;
  --el-pagination-button-color: #5a6c7d;
  --el-pagination-button-bg-color: #f8f9fa;
  --el-pagination-button-disabled-color: #cbd5e0;
  --el-pagination-button-disabled-bg-color: #f1f5f9;
  --el-pagination-hover-color: #ff6b35;
  --el-pagination-hover-bg-color: rgba(255, 107, 53, 0.1);
}

.pagination-section :deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.pagination-section :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
}

.pagination-section :deep(.el-pagination .el-pager li:hover) {
  background: rgba(255, 107, 53, 0.1);
  color: #ff6b35;
  transform: translateY(-2px);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #7f8c8d;
}

.empty-icon {
  margin-bottom: 24px;
  color: #cbd5e0;
}

.empty-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.empty-desc {
  font-size: 16px;
  margin-bottom: 32px;
  color: #7f8c8d;
}

.empty-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-section {
    margin-bottom: 25px;
  }
  
  .filter-section :deep(.el-card__body) {
    padding: 20px;
  }
  
  .filter-section :deep(.el-form) {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-section :deep(.el-form-item) {
    min-width: auto;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    margin-bottom: 25px;
  }
  
  .section-header h2 {
    font-size: 24px;
  }
  
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
  
  .product-card {
    border-radius: 12px;
  }
  
  .product-image {
    height: 200px;
  }
  
  .product-info {
    padding: 16px;
  }
  
  .product-title {
    font-size: 15px;
    min-height: 40px;
  }
  
  .current-price {
    font-size: 20px;
  }
  
  .product-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .product-actions .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .products-page {
    padding: 15px;
  }
  
  .filter-section {
    margin-bottom: 20px;
  }
  
  .filter-section :deep(.el-card__body) {
    padding: 15px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .product-card {
    border-radius: 12px;
  }
  
  .product-image {
    height: 220px;
  }
  
  .product-info {
    padding: 18px;
  }
  
  .product-title {
    font-size: 16px;
    min-height: 44px;
  }
  
  .current-price {
    font-size: 22px;
  }
  
  .product-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  
  .product-actions .el-button {
    font-size: 12px;
    padding: 8px 16px;
  }
  
  .section-header h2 {
    font-size: 20px;
  }
}
</style> 